import { Injectable } from "@nestjs/common";
import { UserRepository } from "../repositories/user.repo";
import { User } from "../entities/user.entity";
import { CloudApiService } from "../../core/cloudApi.service";
import { Request } from "express";
import { log } from "console";

@Injectable()
export class AuthService {
  constructor(
    private readonly userRepo: UserRepository,
    private readonly cloudApi: CloudApiService,
  ) {}

  async validateUser(token: string): Promise<User | null> {
    try {
      // 尝试云 API 验证
      console.log('Validating token',token);
      
      const cloudUser = await this.cloudApi.validateToken(token);
      if (!cloudUser) {
        console.error('Cloud API returned null for token validation');
        return null;
      } 

      console.log('Cloud API returned user:', cloudUser);
      let user = await this.userRepo.findUserById(cloudUser.id);
      if (!user) {
        // 如果用户不存在，创建新用户
        user = await this.userRepo.upsertUser({
          id: cloudUser.id,
          username: cloudUser.username, // 使用 Cloud API 返回的 username
        });
      }
      return user;
      
    } catch (error) {
      console.error('Error during token validation:', error);
      throw new Error(`认证服务异常: ${error.message}`);
    }
  }

  extractToken(request: Request): string | null {
    const authHeader = request.headers.authorization;
    if (!authHeader || !authHeader.startsWith('Bearer ')) return null;
    return authHeader.split(' ')[1];
  }

  async findUserById(userId: string): Promise<User | null> {
    console.log('Finding user by ID:', userId);
    return this.userRepo.findUserById(userId);
  }

  async saveUser(userData: { id: string; username: string }): Promise<User> {
    return this.userRepo.upsertUser(userData);
  }
}